// ============ 全局变量 ============
const ORIGIN = window.location.origin || '';
const API_BASE_URL = /^https?:/i.test(ORIGIN)
  ? ORIGIN
  : (localStorage.getItem('apiBaseUrl') || 'http://localhost:8080');
const url = `${API_BASE_URL}/api/rest/user`;
// 获取新增按钮的DOM
let addForm = document.getElementById('add-form');
const editForm = document.getElementById('edit-form');
let gridInstance = null;
let userData = null; // <= 编辑功能将依赖此缓存
// 认证令牌（如存在则自动附带）
const authToken = localStorage.getItem('token');
const authHeaders = authToken ? { 'Authorization': `Bearer ${authToken}` } : {};
// 下拉选项加载状态
let deptOptionsLoaded = false;
let roleOptionsLoaded = false;

// 列表表头及操作按钮配置
let columns = [
      { name: '#', id: 'id', width: '8%' },
      { name: '用户名', id: 'username', sort: true },
      { name: '姓名', id: 'name', sort: true },
      { name: '邮箱', id: 'email', sort: true },
      { name: '电话', id: 'phone', sort: true },
      { name: '创建时间', id: 'createAt', sort: true },
      { name: '状态', id: 'enableState', sort: true },
      { name: '部门', id: 'dept.name', sort: true },
      {
        name: '操作',
        id: 'actions',
        width: '20%',
        formatter: (_, row) => gridjs.html(`
            <button type="button" data-bs-toggle="modal" data-bs-target="#editModal" onclick="openEdit('${Number(row.cells[0].data)}')" class="btn btn-sm btn-outline-primary m-1"><i class="fas fa-edit"></i> 编辑</button>
            <button type="button" onclick="toggle('${Number(row.cells[0].data)}')" class="btn btn-sm btn-outline-${row.cells[6].data === '启用' ? 'danger' : 'success'} m-1"><i class="fas fa fa-exchange"></i> ${row.cells[6].data === '启用' ? '停用' : '启用'}</button>
        `)
      }
    ]


    // ============ 登录状态校验 ============
if (localStorage.getItem('user') !== 'true') {
  alert('请先登录系统！');
  window.location.href = 'login.html';
  // 阻止后续代码执行
  throw new Error('未登录，已跳转');
}

// 简易预警提示渲染
function showAlert(message, type, container) {
  if (!container) return;
  container.innerHTML = `
    <div class="alert alert-${type} alert-dismissible fade show" role="alert">
      ${message}
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  `;
}

// 在url末尾添加请求参数
function addQueryParam(prevUrl, param) {
    let separator = prevUrl.indexOf('?') !== -1 ? '&' : '?';
    return prevUrl + separator + param;
}

// 使用gridjs初始化表格
function initGrid() {
  if (gridInstance) {
    gridInstance.destroy(); // 销毁旧实例（用于刷新时重建）
  }

  gridInstance = new gridjs.Grid({
    columns: columns,
    server: {
        url: url,
        then: data => {
            // === 修复: 将数据缓存到 userData 供编辑时使用 ===
            userData = data.content; 
            return data.content.map(
                user => [
                    user.id,
                    user.username,
                    user.name,
                    user.email,
                    user.phone,
                    user.createAt,
                    user.enableState,
                    user.dept.name
                ]
            )
        },
        total: data => data.totalElements
    },
    pagination: {
      limit: 5, // 每页5条
      server: {
        url: (prev, page, limit) => addQueryParam(prev, `size=${limit}&page=${page}`)
      }
    },
    search: true, // 启用搜索
    sort: true,   // 启用排序
    language: {
      search: {
        placeholder: '搜索用户...'
      },
      pagination: {
        previous: '上一页',
        next: '下一页',
        showing: '显示第',
        of: '条，共',
        to: '至',
        results: '条记录'
      }
    }
  }).render(document.getElementById("gridjs-container"));
}

document.addEventListener('DOMContentLoaded', function() {
  initGrid();
  initDept();
  initRole();
});

// 获取部门列表
function initDept() {
    fetch(`${API_BASE_URL}/api/rest/dept/all`, { headers: authHeaders, credentials: 'include' })
            .then((response) => response.json())
            .then((data) => {
              // === 修复: 重新检查 addForm 和 editForm 是否存在 ===
              addForm = document.getElementById('add-form');
              // const editForm = document.getElementById('edit-form'); // 已在全局定义
              let addSelectElement = addForm ? addForm.querySelector('[name="deptId"]') : null;
              let editSelectElement = editForm ? editForm.querySelector('[name="deptId"]') : null; 
              
              if (addSelectElement) addSelectElement.innerHTML = '';
              if (editSelectElement) editSelectElement.innerHTML = '';

              data.forEach(item => {
                let option = document.createElement('option');
                option.value = String(item.id);
                option.innerText = item.name;
                
                let addOption = option.cloneNode(true);
                let editOption = option.cloneNode(true);

                if (addSelectElement) addSelectElement.appendChild(addOption);
                if (editSelectElement) editSelectElement.appendChild(editOption);
              });
              deptOptionsLoaded = true;
            })
            .catch(error => {
              console.error('Error:', error);
            });
}
// 获取角色列表
function initRole() {
    fetch(`${API_BASE_URL}/api/rest/role/all`, { headers: authHeaders, credentials: 'include' })
        .then((response) => response.json())
        .then((data) => {
            // === 修复: 重新检查 addForm 和 editForm 是否存在 ===
            addForm = document.getElementById('add-form');
            // const editForm = document.getElementById('edit-form'); // 已在全局定义
            let addSelectElement = addForm ? addForm.querySelector('[name="roleId"]') : null;
            let editSelectElement = editForm ? editForm.querySelector('[name="roleId"]') : null;

            if (addSelectElement) addSelectElement.innerHTML = '';
            if (editSelectElement) editSelectElement.innerHTML = '';

            data.forEach(item => {
            let option = document.createElement('option');
                option.value = String(item.id);
                option.innerText = item.name;

                let addOption = option.cloneNode(true);
                let editOption = option.cloneNode(true);

                if (addSelectElement) addSelectElement.appendChild(addOption);
                if (editSelectElement) editSelectElement.appendChild(editOption);
            });
            roleOptionsLoaded = true;
        })
        .catch(error => {
            console.error('Error:', error);
        });
}
// 表单数据转换成json格式
function formJsonData(form) {
    const jsonData = {}
    const formData = new FormData(form);
    formData.forEach((value, key) => {
    if (!jsonData[key]) {
        jsonData[key] = formData.getAll(key).length > 1 ? formData.getAll(key) : formData.get(key);
    }
    });
    return jsonData;
}

// 等待下拉选项加载完成
function waitForSelects(timeout = 3000) {
  return new Promise(resolve => {
    if (deptOptionsLoaded && roleOptionsLoaded) return resolve();
    const start = Date.now();
    const timer = setInterval(() => {
      if (deptOptionsLoaded && roleOptionsLoaded || Date.now() - start >= timeout) {
        clearInterval(timer);
        resolve();
      }
    }, 50);
  });
}

// 文件上传（新增表单头像）
const addAvatarInput = document.getElementById('fileInput');
if (addAvatarInput) {
  addAvatarInput.addEventListener('change', function () {
      const file = addAvatarInput.files[0];
      if (!file) return;
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', '头像');
      fetch(`${API_BASE_URL}/api/rest/attachment`, {
          method: 'POST',
          body: formData,
          headers: authHeaders,
          credentials: 'include'
      }).then(response => response.json())
      .then(data => {
          if (addForm) {
              addForm.querySelector('[name="avatar"]').value = data.id
          }
      })
      .catch(err => console.error('上传头像失败:', err));
  });
}

// 文件上传（编辑表单头像）
const editAvatarInput = document.getElementById('e_fileInput');
if (editAvatarInput) {
  editAvatarInput.addEventListener('change', function () {
      const file = editAvatarInput.files[0];
      if (!file) return;
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', '头像');
      fetch(`${API_BASE_URL}/api/rest/attachment`, {
          method: 'POST',
          body: formData,
          headers: authHeaders,
          credentials: 'include'
      }).then(response => response.json())
      .then(data => {
          if (editForm) {
            editForm.querySelector('[name="avatar"]').value = data.id
          }
      })
      .catch(err => console.error('上传头像失败:', err));
  });
}

// 监听新增按钮
// === 修复: 再次检查 addForm 是否存在 ===
if (addForm) {
  addForm.addEventListener('submit', (event) => {
      event.preventDefault();
  if (addForm.checkValidity()) {
      let jsonData = formJsonData(addForm)
      fetch(url, {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
          ...authHeaders
      },
      credentials: 'include',
      body: JSON.stringify(jsonData)
      }).then(response => {
      if (response.ok) {
          const userModal = document.getElementById('addModal');
          bootstrap.Modal.getInstance(userModal).hide();
  
          if (gridInstance) gridInstance.forceRender();
  
          Toastify({
              text: "成功添加新用户",
              duration: 3000,
              close: true,
              backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
              style: {
              borderRadius: "10px"
              }
          }).showToast();
      } else {
          response.json().then(data => {
              showAlert(data.message || '添加用户失败', 'danger', document.getElementById('alertAddMessage'))
          })
          }
      });
  } else {
      addForm.classList.add('was-validated');
  }
  });
} else {
  // 这个警告现在是预期的，如果 HTML 没修复
  console.warn('addForm 不存在，新增功能未绑定。请检查 user.html 中 id="add-form" 是否存在且唯一。');
}

// 编辑表单提交
// === 修复: 再次检查 editForm 是否存在 ===
if (editForm) {
  editForm.addEventListener('submit', (event) => {
      event.preventDefault();
      if (editForm.checkValidity()) {
          let jsonData = formJsonData(editForm)
          fetch(`${url}/${jsonData.id}`, {
              method: 'PATCH',
              headers: {
                  'Content-Type': 'application/json',
                  ...authHeaders
              },
              credentials: 'include',
              body: JSON.stringify(jsonData)
          }).then(response => {
              if (response.ok) {
                  const userModal = document.getElementById('editModal');
                  bootstrap.Modal.getInstance(userModal).hide();
  
                  if (gridInstance) gridInstance.forceRender();
  
                  Toastify({
                      text: "编辑用户成功",
                      duration: 3000,
                      close: true,
                      backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                      style: {
                          borderRadius: "10px"
                      }
                  }).showToast();
              } else {
                  response.json().then(data => {
                      showAlert(data.message || '编辑用户失败', 'danger', document.getElementById('alertEditMessage'))
                  })
              }
          });
      } else {
          editForm.classList.add('was-validated');
      }
  })
} else {
  // 这个警告现在是预期的，如果 HTML 没修复
  console.warn('editForm 不存在，编辑功能未绑定。请检查 user.html 中 id="edit-form" 是否存在且唯一。');
}


// === 修复: 移除 fetchUserById 函数，因为它导致 405 错误 ===
// async function fetchUserById(uid) { ... } // 已删除


// 打开编辑并填充表单
async function openEdit(userId) {
  if (!editForm) { 
      console.warn('editForm 不存在'); 
      return; 
  }

  // 1. 重置表单，清除旧数据和验证状态
  editForm.reset(); 
  editForm.classList.remove('was-validated');
  const alertContainer = document.getElementById('alertEditMessage');
  if (alertContainer) alertContainer.innerHTML = '';
  
  try {
    // === 修复: 仅从 userData 缓存中查找用户 ===
    const user = (userData && Array.isArray(userData)) 
        ? userData.find(i => String(i.id) === String(userId)) 
        : null;

    // 2. 如果缓存中没有找到（例如用户在其他分页），则显示错误并停止
    if (!user) {
        console.error(`无法在 userData 缓存中找到 ID 为 ${userId} 的用户。`);
        showAlert('无法在当前分页缓存中找到该用户。请尝试刷新页面，或在用户所在的正确分页上进行编辑。', 'danger', alertContainer);
        return;
    }

    // 3. (如果找到了) 填充表单数据
    editForm.elements['id'].value = userId;
    editForm.querySelector('[name="username"]').value = user.username || '';
    editForm.querySelector('[name="name"]').value = user.name || '';
    editForm.querySelector('[name="phone"]').value = user.phone || '';
    editForm.querySelector('[name="email"]').value = user.email || '';
    // 填充已有头像ID，防止头像丢失
    editForm.querySelector('[name="avatar"]').value = user.avatar || '';

    // 4. 等待下拉选项加载完成后再设置选中值
    await waitForSelects();

    if (user.dept && user.dept.id != null) {
      const deptSelect = editForm.querySelector('[name="deptId"]');
      if (deptSelect) deptSelect.value = String(user.dept.id);
    }
    if (user.role && user.role.id != null) {
      const roleSelect = editForm.querySelector('[name="roleId"]');
      if (roleSelect) roleSelect.value = String(user.role.id);
    }

  } catch (e) {
    // 捕获 (waitForSelects) 等待期间可能发生的意外错误
    console.error('打开编辑时发生意外错误:', e);
    showAlert('加载用户信息时发生意外错误，请稍后重试', 'danger', alertContainer);
  }
}

//实现切换用户状态功能
function toggle(id) {
    fetch(`${url}/${id}/toggle`, { method: 'PATCH', headers: authHeaders, credentials: 'include' })
    .then(async (response) => {
        if (response.ok) {
            // (已修复) 使用 forceRender 刷新表格
            if (gridInstance) {
                gridInstance.forceRender();
            }
            Toastify({
                text: "状态已更新",
                duration: 2000,
                close: true,
                backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                style: { borderRadius: "10px" }
            }).showToast();
        } else {
            const data = await response.json().catch(() => ({}));
            Toastify({
                text: data.message || "状态切换失败",
                duration: 3000,
                close: true,
                backgroundColor: "linear-gradient(to right, #ff5f6d, #ffc371)",
                style: { borderRadius: "10px" }
            }).showToast();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Toastify({
            text: "网络错误：状态切换失败",
            duration: 3000,
            close: true,
            backgroundColor: "linear-gradient(to right, #ff5f6d, #ffc371)",
            style: { borderRadius: "10px" }
        }).showToast();
    });
}

// ============ 用户登出功能 ============
function logout() {
    if (confirm("确定要退出登录吗？")) {
        localStorage.removeItem('user');
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        Toastify({
            text: "已退出登录",
            duration: 2000,
            close: true,
            backgroundColor: "linear-gradient(to right, #ff5f6d, #ffc371)",
            style: { borderRadius: "10px" }
        }).showToast();
        setTimeout(() => {
            window.location.href = "login.html";
        }, 1500);
    }
}